package it.anyplace.anyspeed;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends Activity {

//	private final DateFormat dateFormat = new SimpleDateFormat("H:m:s");

	private final String TAG = "MAIN";

	private float upperLimitMs = 40 / 3.6f;
	private float lowerLimitMs = 30 / 3.6f;

	private MirrorTextView speedMeter, logTextView;
	private MirrorDigitalClock clock;
	
	private SoundPool soundPool= new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
	

	private void updateSpeed(float speedMs) {
		Log.d(TAG, "updating speed : " + speedMs);
		float speedKmh = speedMs * 3.6f;
		String text = Integer.toString(Math.round(speedKmh));
		speedMeter.setText(text);
		if (speedMs > upperLimitMs) {
			speedMeter.setTextColor(Color.RED);
			logToScreen("speed above " + upperLimitMs + " m/s");
			soundPool.play(sndHi, 1, 1, 0, 0, 1);
		} else if (speedMs < lowerLimitMs) {
			logToScreen("speed below " + lowerLimitMs + " m/s");
			speedMeter.setTextColor(Color.BLUE);
			soundPool.play(sndLo, 1, 1, 0, 0, 1);
		} else {
			speedMeter.setTextColor(Color.GREEN);
			clearScreenLog();
		}

		// String time = dateFormat.format(new Date());
		// timeTextView.setText(time);
	}

	private void logToScreen(String text) {
		logTextView.setText(text);
	}

	private void clearScreenLog() {
		logToScreen("");
	}

//	private void updateTextSize() {
//		float height = speedMeter.getHeight(), size = height * 0.95f;
//		Log.d(TAG, "updated size = " + size + " for screen size = " + height);
//		speedMeter.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
//	}

//	private boolean gpsLogIsShowing = true;
	private int sndLo,sndHi;
	
	private boolean isMirror=false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "initializing");
		try {
			sndHi=soundPool.load(getApplicationContext(), R.raw.snd_hi, 1);
			sndLo=soundPool.load(getApplicationContext(), R.raw.snd_lo, 1);
			
			
			setContentView(R.layout.activity_main);
			clock=(MirrorDigitalClock) findViewById(R.id.digitalClock);
			logTextView = (MirrorTextView) findViewById(R.id.logTextView);
			// timeTextView = (TextView) findViewById(R.id.timeTextView);

			speedMeter = (MirrorTextView) findViewById(R.id.speedMeter);
			DisplayMetrics displayMetrics = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
			int textSize= displayMetrics.heightPixels-50;
			int padding=-Math.round(textSize*0.15f);
//			int textSize= speedMeter.getHeight();
			speedMeter.setTextSize(TypedValue.COMPLEX_UNIT_PX,textSize);
			speedMeter.setPadding(0, padding, 0, 0);
			Log.i(TAG, "set text size to "+textSize+" , padding to "+padding);
			
			speedMeter.setOnTouchListener(new OnTouchListener() {
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					if(event.getAction()==MotionEvent.ACTION_UP){
						isMirror = !isMirror;
						speedMeter.setMirror(isMirror);
						logTextView.setMirror(isMirror);
						clock.setMirror(isMirror);
						ViewGroup viewGroup = (ViewGroup) findViewById (R.id.mainLayout);
						viewGroup.invalidate();
					}
					return true;
				}
			});
			
//			ViewGroup viewGroup = (ViewGroup) findViewById (R.id.mainLayout);
//			viewGroup.invalidate();
			
			Log.d(TAG, "initializing location listener");
			LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			locationManager.requestLocationUpdates(
					LocationManager.GPS_PROVIDER, 1500, 10,
					new LocationListener() {

						@Override
						public void onLocationChanged(Location newLocation) {
//							if (gpsLogIsShowing) {
//								clearScreenLog();
//								gpsLogIsShowing = false;
//							}
							if (newLocation.hasSpeed()) {
								updateSpeed(newLocation.getSpeed());
							} else {
								Log.d(TAG, "skipping no-speed location update");
							}
						}

						@Override
						public void onProviderDisabled(String arg0) {
							Log.w(TAG, "GPS went down!");
							logToScreen("GPS sensor inactive!");
//							gpsLogIsShowing = true;
						}

						@Override
						public void onProviderEnabled(String arg0) {
							Log.i(TAG, "GPS back up!");
							logToScreen("waiting for gps data ...");
//							gpsLogIsShowing = true;
						}

						@Override
						public void onStatusChanged(String arg0, int arg1,
								Bundle arg2) {
							Log.i(TAG, "GPS status changed . . ");
						}

					});
		} catch (Exception ex) {
			Log.e(TAG, "error douring initialization", ex);
			logToScreen("initialization error " + ex.toString() + " !");
		}
		Log.d(TAG, "ready");
		logToScreen("waiting for gps data ...");
//		gpsLogIsShowing = true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}
